package com.yfuxdeer.youchat.ui.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import android.app.Fragment;

import android.os.Handler;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.yfuxdeer.youchat.service.UserService;
import com.yfuxdeer.youchat.R;
import com.yfuxdeer.youchat.activity.RegisterActivity;
import com.yfuxdeer.youchat.pojo.User;

import java.util.regex.Pattern;

public class RegisterStep2 extends Fragment {

    private static final String TAG = RegisterStep2.class.getSimpleName();
    private RegisterActivity activity;
    private EditText password;
    private EditText password_again;
    private Button register;
    private ImageButton eye1;
    private ImageButton eye2;
    private UserService userService = new UserService();
    boolean eye_b1 = true;
    boolean eye_b2 = true;

    public RegisterStep2() {

    }

    public static RegisterStep2 newInstance() {
        RegisterStep2 fragment = new RegisterStep2();
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = (RegisterActivity) activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_register_step2, container, false);
        //注册广播
        activity.registerReceiver(registerReceiver, new IntentFilter("com.yfuxdeer.youchat.registerReceiver"));
        findViews(view);
        setListeners();
        return view;
    }

    private void findViews(View view) {
        register = view.findViewById(R.id.register);
        password = view.findViewById(R.id.password);
        password_again = view.findViewById(R.id.password_again);
        eye1 = view.findViewById(R.id.eye1);
        eye2 = view.findViewById(R.id.eye2);
    }

    private void setListeners() {
        eye1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (eye_b1) {
                    eye1.setImageDrawable(activity.getDrawable(R.drawable.hide_password));
                    password.setInputType(InputType.TYPE_CLASS_TEXT);
                } else {
                    eye1.setImageDrawable(activity.getDrawable(R.drawable.show_password));
                    password.setInputType(0x00000081);
                }
                eye_b1 = !eye_b1;
                password.setSelection(password.getText().length());
            }
        });
        eye2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (eye_b2) {
                    eye2.setImageDrawable(activity.getDrawable(R.drawable.hide_password));
                    password_again.setInputType(InputType.TYPE_CLASS_TEXT);
                } else {
                    eye2.setImageDrawable(activity.getDrawable(R.drawable.show_password));
                    password_again.setInputType(0x00000081);
                }
                eye_b2 = !eye_b2;
                password_again.setSelection(password_again.getText().length());
            }
        });
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String password1 = password.getText().toString();
                String password2 = password_again.getText().toString();
                if (!validatePassword(password1)) {
                    Toast.makeText(activity,
                            "密码太弱,试试6位以上数字、字母、符号的组合", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!password1.equals(password2)) {
                    Toast.makeText(activity,
                            "两次密码不一致", Toast.LENGTH_SHORT).show();
                    return;
                }

                User user = new User();
                if (activity.getPhone_().contains("@")) {
                    user.setEmail(activity.getPhone_());
                    user.setPhone("暂未设置");
                } else {
                    user.setPhone(activity.getPhone_());
                    user.setEmail("暂未设置邮箱");
                }
                user.setPassword(password1);

                //启动服务完成网络请求
                Intent intent = new Intent(activity, UserService.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("method", UserService.METHOD.REGISTER);
                bundle.putSerializable("user", user);
                intent.putExtras(bundle);
                activity.startService(intent);

            }
        });
    }

    private boolean validatePassword(String password) {
        return Pattern.matches("^(?![0-9]+$)[0-9A-Za-z-`~!@#$%^&*()_+=;:/?.,*]{6,20}$", password);
    }

    /**
     * 注册广播接受者
     */
    private BroadcastReceiver registerReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            UserService.RESULT result = (UserService.RESULT) bundle.getSerializable("result");
            View view_;
            PopupWindow popupWindow;
            Button button;
            TextView tip;
            TextView textView;
            switch (result) {
                case SUCCESS:
                    String username = bundle.getString("username");
                    view_ = activity.getLayoutInflater().inflate(R.layout.pop_register_success, null);
                    popupWindow = new PopupWindow(view_, ViewGroup.LayoutParams.MATCH_PARENT
                            , ViewGroup.LayoutParams.MATCH_PARENT);
                    popupWindow.setFocusable(true);
                    popupWindow.showAsDropDown(register);
                    button = view_.findViewById(R.id.toLogin);
                    textView = view_.findViewById(R.id.username);
                    textView.setText(username);
                    button.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            popupWindow.dismiss();
                            activity.finish();
                        }
                    });
                    break;
                case ALREDY_REGISTER:
                    String password = bundle.getString("password");
                    view_ = activity.getLayoutInflater().inflate(R.layout.pop_register_success, null);
                    popupWindow = new PopupWindow(view_, ViewGroup.LayoutParams.MATCH_PARENT
                            , ViewGroup.LayoutParams.MATCH_PARENT);
                    popupWindow.setFocusable(true);
                    System.out.println("activity is : " + activity);
                    System.out.println("register is : " + register);
                    popupWindow.showAsDropDown(register);
                    button = view_.findViewById(R.id.toLogin);
                    tip = view_.findViewById(R.id.tip);
                    textView = view_.findViewById(R.id.username);
                    textView.setText(password);
                    tip.setText("修改密码成功，你的新密码是：");
                    button.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            popupWindow.dismiss();
                            activity.finish();
                        }
                    });
                    break;
                case NETWORK_EXCEPTION:
                    Toast.makeText(activity, "网络异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
}